package com.android.quizvoctrainer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RunTestActivity extends Activity {
	private boolean debugMode = false;
	private TextView tvTitle;
	private TextView tvQuestionNumber;
	private TextView tvQuestionLabel;
	private TextView tvQuestion;
	private Button btCheck;
	private EditText etAnswer;
	private TextView tvBadAnswer;
	private TextView tvGoodAnswerIs;
	private TextView tvAnswerForOtherQuestion;
	private CharSequence path = "";
	private CharSequence listsPath = "";
	private CharSequence currentListFilename;
	private QuizVocList list;
	private int index = 0;
	private int numberOfQuestionPerTest = 0;
	private int currentQuestionNumber = 0;
	private int numberOfGoodAnswers = 0;
	private int numberOfAnsweredQuestions = 0;
	private int numberOfQuestions = 0;
	private Toast goodToast;
	private AlertDialog endTestDialog;
	private boolean checkbuttonmodecheck = true;
	private boolean ignoreCase = true;
	private int randomDispersionRange = 1;
	private String answer;
	private int percentToBypassNewWords = 70;
	private int percentToBypassPerfectStatsWords = 90;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.runtest);
	    initApplication();
	}
	private void initApplication() {
		Intent intent = getIntent();
		currentListFilename = intent.getCharSequenceExtra(Utils.currentListFilenameKey);
		numberOfQuestions = intent.getIntExtra(Utils.numberOfQuestionsKey, 0);
		numberOfQuestionPerTest = numberOfQuestions;
        tvTitle = (TextView)findViewById(R.id.texttitle);
        tvQuestionNumber = (TextView)findViewById(R.id.textquestionnumber);
        tvQuestionLabel = (TextView)findViewById(R.id.textquestionlabel);
        tvQuestion = (TextView)findViewById(R.id.textquestion);
        btCheck = (Button)findViewById(R.id.buttoncheck);
        btCheck.setOnClickListener(bCheckOnClick);
        etAnswer = (EditText)findViewById(R.id.editanswer);
        tvBadAnswer = (TextView)findViewById(R.id.textbad);
        tvGoodAnswerIs = (TextView)findViewById(R.id.textanswer);
        tvAnswerForOtherQuestion = (TextView)findViewById(R.id.textanswerforotherquestion);
        path = getExternalFilesDir(null).getPath();
        listsPath = path + "/lists";
        goodToast = Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.good_answer), Toast.LENGTH_SHORT);
        goodToast.setGravity(Gravity.CENTER, 0, 0);
        createEndTestDialog();
        //bRunTest = (Button)findViewById(R.id.buttonrun);
        //bRunTest.setOnClickListener(bRunTestOnClick);
        //////////////////////////////////////////////
        list = Utils.loadCurrentListFromFile(listsPath, currentListFilename);
        index = 0;
        currentQuestionNumber = 1;
        updateScreen();
	};
    private void debug(String text) {
    	Toast.makeText(getBaseContext(), text,Toast.LENGTH_LONG).show();
    }
    private float getAverage() {
    	int average = (10000 * numberOfGoodAnswers / numberOfAnsweredQuestions);
    	return (float)average / 100;
    }
	private void updateScreen() {
		String text; 
		text = list.getName().toString() + " (" + list.getLength() + ")";
		tvTitle.setText(text);
		updateTvQuestionNumber();
		tvQuestionLabel.setText(list.getTitle());
		if (debugMode) {
			tvQuestion.setText(list.getItem(index).getQuestion() + " [" + list.getItem(index).getPopularity() + "]  [" + list.getItem(index).getStats() + "]");
		} else {
			tvQuestion.setText(list.getItem(index).getQuestion());
		}
		etAnswer.setText("");
		checkbuttonmodecheck = true;
		tvBadAnswer.setText("");
		tvGoodAnswerIs.setText("");
		tvAnswerForOtherQuestion.setText("");
	}
	private void updateTvQuestionNumber() {
		String text = getApplicationContext().getString(R.string.question) + " " + currentQuestionNumber + "/" + numberOfQuestions;
		if (numberOfAnsweredQuestions > 0) {
			text = text + " (" + getApplicationContext().getString(R.string.average) + " : " + getAverage() + "%)"; 
		}
		tvQuestionNumber.setText(text);
	}
	private OnClickListener bCheckOnClick = new OnClickListener() {
		public void onClick(View v) {
			answer = etAnswer.getText().toString();
			if (checkbuttonmodecheck) {
				if (checkAnswer(answer, index)) {
					goodAnswer();
				} else {
					checkbuttonmodecheck = false;
					badAnswer();
				}
			} else {
				goOn();
			}
		}
	};
	private boolean checkAnswer(String answer, int index) {
		if (answer.trim().equals(list.getItem(index).getAnwser().toString().trim())) {
			return true;
		} else if (ignoreCase && answer.trim().toLowerCase().equals(list.getItem(index).getAnwser().toString().trim().toLowerCase())) {
			return true;
		} else {
			return false;
		}
	}
	private void goodAnswer() {
		numberOfGoodAnswers ++;
		if (debugMode) debug("pop offset = " + list.setResultImpact(true, index));
		else list.setResultImpact(true, index);
		list.sortListByPop();
		Utils.saveListToFile(list, listsPath, list.getFilename());
		goodToast.show();
		index = computeNewIndex();
		goOn();
	}
	private void badAnswer() {
		String text = getApplicationContext().getString(R.string.bad_answer) + ". " + getApplicationContext().getString(R.string.correct_answer_is) + " :";
		tvBadAnswer.setText(text);
		tvGoodAnswerIs.setText(list.getItem(index).getAnwser());
		if (debugMode) debug("pop offset = " + list.setResultImpact(false, index));
		else list.setResultImpact(false, index);
		int otherQuestionIndex = isAnswerForOtherQuestion(answer, index);
		if (otherQuestionIndex > -1) {
			// The user gave an answer to another question
			// We tell him/her and gave a bad answer in stats to that question as well
			text = "\"" + list.getItem(otherQuestionIndex).getAnwser() + "\" " + getApplicationContext().getString(R.string.is_answer_of) + " \"" + list.getItem(otherQuestionIndex).getQuestion() + "\"";
			tvAnswerForOtherQuestion.setText(text);
			list.setResultImpact(false, otherQuestionIndex);
		}
		list.sortListByPop();
		Utils.saveListToFile(list, listsPath, list.getFilename());
		index = computeNewIndex();
	}
	private int isAnswerForOtherQuestion(String answer, int index) {
		int result = -1;
		for (int i=0;i < list.getLength(); i++) {
			if (i != index) {
				if (checkAnswer(answer, i)) {
					result = i;
				}
			}
		}
		return result;
	}
	private void goOn() {
		numberOfAnsweredQuestions ++;
		if (currentQuestionNumber >= numberOfQuestions) {
			updateTvQuestionNumber(); // So the average is updated on the background screen behind the alert dialog
			endTest();
		} else {
			currentQuestionNumber ++;
			updateScreen();
		}
	}
	private void endTest() {
		CharSequence result = getApplicationContext().getString(R.string.your_result) + " : " 
			+ numberOfGoodAnswers + "/" + numberOfQuestions
			+ " (" + getAverage() + "%)";
		endTestDialog.setMessage(result);
		endTestDialog.show();
	}
	private void quitRunTestActivity() {
		finish();
	}
	private void extendTest() {
		numberOfQuestions = numberOfQuestions + numberOfQuestionPerTest;
		currentQuestionNumber ++;
		updateScreen();
	}
	private int computeNewIndex() {
		int power = 5;
		if (randomDispersionRange == 0) power = 8;
		else if (randomDispersionRange == 2) power = 2;
		int newIndex = (int)(Math.pow(Math.random(),power) * list.getLength());
		if (list.getItem(newIndex).getStats().length() == 0) {
			// If word was never asked yet, can be bypassed to avoid to be snowed under with new words
			if (Math.random() * 100 < percentToBypassNewWords) {
				newIndex = computeNewIndex();
			}
		} else if (list.getItem(newIndex).getStats().length() > 0 && list.getItem(newIndex).getStats().charAt(list.getItem(newIndex).getStats().length() - 1) == '1') {
			// If last stats are good, can be bypassed and popularity raised like it was correctly answered.
			// percent for bypass = percentToBypassPerfectStatsWords / 10 * length of last correct sequence (1)
			if (Math.random() * 100 < percentToBypassPerfectStatsWords) {
				list.setResultImpact(true, newIndex);
				newIndex = computeNewIndex();
			}
		}
		return newIndex;
	}
	private void createEndTestDialog() {
		endTestDialog = new AlertDialog.Builder(this).create();  
		endTestDialog.setTitle(R.string.test_finished);
		WindowManager.LayoutParams WMLP = endTestDialog.getWindow().getAttributes();
		WMLP.gravity = Gravity.TOP;
		WMLP.y = 40;   //y position
		endTestDialog.getWindow().setAttributes(WMLP);
		endTestDialog.setButton(getApplicationContext().getString(R.string.give_up), new DialogInterface.OnClickListener() {  
		      public void onClick(DialogInterface dialog, int which) {
		    	  quitRunTestActivity();
		      } 
		});
		String buttonLabel = getApplicationContext().getString(R.string.more_please);
		buttonLabel = buttonLabel.replace("X", numberOfQuestionPerTest + "");
		endTestDialog.setButton2(buttonLabel, new DialogInterface.OnClickListener() {  
		      public void onClick(DialogInterface dialog, int which) {
		    	  extendTest();
		      } 
		});   
		
	}
	
}
